package com.xscr.api.service.order;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.rop.annotation.HttpAction;
import com.rop.annotation.IgnoreSignType;
import com.rop.annotation.NeedInSessionType;
import com.rop.annotation.ServiceMethod;
import com.rop.annotation.ServiceMethodBean;
import com.rop.response.Response;
import com.xscr.api.pojo.AddressDTO;
import com.xscr.api.pojo.OrderDTO;
import com.xscr.api.pojo.OrderDetailDTO;
import com.xscr.api.pojo.ProductDetailDTO;
import com.xscr.api.pojo.ProductExtDTO;
import com.xscr.api.pojo.PromotionDTO;
import com.xscr.api.pojo.SkuDTO;
import com.xscr.api.pojo.SkuExtDTO;
import com.xscr.api.request.AddCartRequest;
import com.xscr.api.request.EvaluationRequest;
import com.xscr.api.request.GetCartRequest;
import com.xscr.api.request.GetOrderDetailRequest;
import com.xscr.api.request.GetOrderRequest;
import com.xscr.mybatis.utility.PageBean;
import com.xscr.order.api.OrderEvaluationService;
import com.xscr.order.api.OrderFormService;
import com.xscr.order.api.OrderItemService;
import com.xscr.order.dto.OrderDto;
import com.xscr.order.po.OrderEvaluation;
import com.xscr.order.po.OrderForm;
import com.xscr.order.po.OrderItem;
import com.xscr.user.po.CuserAddress;
import com.xscr.user.po.User;
import com.xscr.user.service.ICuserAddressService;
import com.xscr.user.service.UserService;

@ServiceMethodBean(version = "1.0", ignoreSign = IgnoreSignType.NO)
public class OrderAction {
	private static final Logger logger=LoggerFactory.getLogger(OrderAction.class);

	@Resource
	OrderFormService orderFormservice;

	@Resource
	OrderItemService orderItemService;

	@Resource
	ICuserAddressService userAddressService;
	
	@Resource
	OrderEvaluationService orderEvaluationService;

	@Resource
	private UserService userService;

	/**
	 * 获取订单列表
	 * 
	 * @param getOrderRequest
	 * @return
	 */
	@ServiceMethod(method = "order.getOrderList", version = "1.0", needInSession = NeedInSessionType.NO, httpAction = HttpAction.GET)
	public Response getOrderList(GetOrderRequest getOrderRequest) {
		Response response = new Response();
		String msg = "";

		Integer page = getOrderRequest.getPageCount();
		Integer status = getOrderRequest.getStatus();
		Long userId = getOrderRequest.getUserId();
		
		if(userId==null||StringUtils.isBlank(userId.toString()))
		{
			response.getResult().setResult("0");
			response.getResult().setMessage("参数不合法");
			return response;
		}

		try {

			PageBean<OrderDto> pageBean = new PageBean<OrderDto>();
			pageBean.setPageSize(10);

			pageBean.setPage(page);
			pageBean = orderFormservice.selectOrderList(pageBean, "", status, "",
					Integer.valueOf(userId.toString()), 0);

			List<OrderDto> orders = pageBean.getResult();
			Map<String, Object> data = new HashMap<String, Object>(5);

			List<OrderDTO> orderList = new ArrayList<OrderDTO>();
			for (OrderDto o : orders) {
				OrderDTO order = new OrderDTO();
				order.setCreateTime(o.getCreateTime().toString());
				order.setOrderAmount(o.getPrice());
				order.setPayWay(1);
				order.setSkuCount(o.getOrderitem().size());
				List<OrderItem> itemList = o.getOrderitem();

				for (OrderItem item : itemList) {
					order.setItemName(item.getSkuName());;
					order.setImgUrl(item.getImageUrl());
					break;
				}

				order.setOrderId(o.getOrderId().toString());
				order.setUserId(o.getUser().getcUserId().longValue());
				order.setStatus(o.getOrderStatus());
				orderList.add(order);
			}

			data.put("orderList", orderList);

			response.setData(data);
		} catch (Exception e) {
			logger.error("getOrderList error", e);
			response.getResult().setResult("0");
			response.getResult().setMessage("获取订单列表错误");
			return response;
		}

		msg = " 获取订单列表成功";
		response.getResult().setResult("1");
		response.getResult().setMessage(msg);
		return response;
	}

	/**
	 * 获取订单详情
	 * 
	 * @param getOrderDetailRequest
	 * @return
	 */
	@ServiceMethod(method = "order.getOrderDetail", version = "1.0", needInSession = NeedInSessionType.NO, httpAction = HttpAction.GET)
	public Response getOrderDetail(GetOrderDetailRequest getOrderDetailRequest) {
		Response response = new Response();
		String msg = "";

		String orderId = getOrderDetailRequest.getOrderId();
		
		if(orderId==null||StringUtils.isBlank(orderId))
		{
			response.getResult().setResult("0");
			response.getResult().setMessage("参数不合法");
			return response;
		}
		
		try {

			OrderForm orderForm = orderFormservice.selectById(orderId);
			if (orderForm == null)
			{
				response.getResult().setResult("0");
				response.getResult().setMessage("订单不存在");
				return response;
			}

			Map<String, Object> data = new HashMap<String, Object>(5);

			OrderDetailDTO orderDetai = new OrderDetailDTO();

			orderDetai.setCouponAmount(orderForm.getCouponPrice());
			orderDetai.setCreateTime(orderForm.getCreateTime().toString());

			orderDetai.setMessage(orderForm.getUserComment());
			orderDetai.setOrderAmount(orderForm.getPrice());
			orderDetai.setOrderId(orderForm.getOrderId().toString());
			orderDetai.setPayWay(orderForm.getPaymentType());
			orderDetai.setProductAmount(orderForm.getDiscountPrice());

			List<OrderItem> itemList = orderItemService
					.selectOrderItemList(Integer.valueOf(orderId));

			orderDetai.setProductCount(itemList.size());
			List<SkuDTO> skuList = new ArrayList<SkuDTO>();
			for (OrderItem item : itemList) {
				SkuDTO sku = new SkuDTO();
				sku.setName(item.getSkuName());
				sku.setCurPrice(item.getFinalPrice());
				sku.setImgUrl(item.getImageUrl());

				orderDetai.setImgUrl(item.getImageUrl());
				int result=orderEvaluationService.countBySkuId(item.getSkuId());
				sku.setIsEvaluated(result>0?true:false);
				sku.setOriPrice(item.getPrice());
				sku.setSkuId(Long.valueOf(item.getSkuId()));
				sku.setStock(item.getSkuQuality());
				skuList.add(sku);
			}
			orderDetai.setSkuList(skuList);
			orderDetai.setStatus(orderForm.getOrderStatus());
			orderDetai.setTransferAmount(new BigDecimal(0));
			orderDetai.setUserId(Long.valueOf(orderForm.getUserId()));
			
			Integer addressId=orderForm.getAddressId();
			if(addressId==null||StringUtils.isBlank(addressId.toString()))
			{
				data.put("orderDetail", orderDetai);
				response.setData(data);
				msg = "获取订单详情成功,但由于地址id为空，所以获取地址信息失败";
				response.getResult().setResult("1");
				response.getResult().setMessage(msg);
				return response;
			}
			// ---------------------dizhi
			CuserAddress addr = userAddressService.getUserAddress(Long
					.valueOf(addressId));
			AddressDTO address = new AddressDTO();
			address.setAddressId(Long.valueOf(orderForm.getAddressId()));

			// address.setAreaId(Long.valueOf(addr.getAreaCode()));
			address.setAreaName(addr.getArea());
			// address.setCityId(Long.valueOf(addr.getCity()));
			address.setCityName(addr.getCity());
			address.setDetailAddress(addr.getAddress());
			// address.setIsDefault(addr.getIsDefault()==0?false:true);
			// address.setProvinceId(Long.valueOf(addr.getProvince()));
			address.setProvinceName(addr.getProvince());
			address.setReceiveMb(addr.getMobile());
			if (orderForm.getUserId() != null) {
				User user=userService.selectByUserId(orderForm.getUserId());
				address.setReceiverName(user.getAccountName());
			}

			data.put("address", address);
			data.put("orderDetail", orderDetai);

			response.setData(data);
		} catch (Exception e) {
			logger.error("getOrderDetail error", e);
			response.getResult().setResult("0");
			response.getResult().setMessage("获取订单详情错误");
			return response;
		}

		msg = "获取订单详情成功";
		response.getResult().setResult("1");
		response.getResult().setMessage(msg);
		return response;
	}

	/**
	 * 删除订单
	 * 
	 * @param getOrderDetailRequest
	 * @return
	 */
	@ServiceMethod(method = "order.deleteOrder", version = "1.0", needInSession = NeedInSessionType.NO, httpAction = HttpAction.POST)
	public Response deleteOrder(GetOrderDetailRequest getOrderDetailRequest) {
		Response response = new Response();
		String msg = "";
		String orderId = getOrderDetailRequest.getOrderId();
		
		if(orderId==null||StringUtils.isBlank(orderId))
		{
			response.getResult().setResult("0");
			response.getResult().setMessage("参数不合法");
			return response;
		}
		
		try {
			OrderForm orderForm = orderFormservice.selectById(orderId);
			if (orderForm == null)
			{
				response.getResult().setResult("0");
				response.getResult().setMessage("订单不存在");
				return response;
			}

			orderFormservice.delete(orderId);

		} catch (Exception e) {
			logger.error("deleteOrder error", e);
			response.getResult().setResult("0");
			response.getResult().setMessage("删除订单错误");
			return response;
		}
		msg = "删除订单成功";
		response.getResult().setResult("1");
		response.getResult().setMessage(msg);
		return response;
	}
	
	/**
	 * 获取订单的评价列表
	 * @param getOrderRequest
	 * @return
	 */
	@ServiceMethod(method = "order.getEvaluationList", version = "1.0", needInSession = NeedInSessionType.NO, httpAction = HttpAction.GET)
	public Response getEvaluationList(GetOrderDetailRequest getOrderDetailRequest) {
		Response response = new Response();
		String msg = "";

		String orderId = getOrderDetailRequest.getOrderId();
		
		if(orderId==null||StringUtils.isBlank(orderId))
		{
			response.getResult().setResult("0");
			response.getResult().setMessage("参数不合法");
			return response;
		}

		try {
			List<Map<String,Object>> list = orderEvaluationService.listEvaluaAndOrderItemByOrderId(Integer.parseInt(orderId));
			
			for(Map<String,Object> map : list){
				if(map.containsKey("sku_id")){
					map.put("countEvaluation", orderEvaluationService.countBySkuId(Integer.parseInt(map.get("sku_id")+"")));
				}else{
					map.put("countEvaluation", 0);
				}
				
				if(!map.containsKey("evaluation_id")){
					map.put("evaluation_id", 0);
					map.put("evaluation_price", 0);
					map.put("evaluation_content","");
				}
				List<String> images = new ArrayList<String>();
				if(map.containsKey("pic_url")){
					
					String picurls[] = (map.get("pic_url")+"").split("###");
					for(String url : picurls){
						if(!url.equals(""))
							images.add(url);
					}					
				}
				map.put("images", images);
			}
			
			Map<String, Object> data = new HashMap<String, Object>(5);

			data.put("list", list);
			response.setData(data);
		} catch (Exception e) {
			logger.error("getEvaluationList error", e);
			response.getResult().setResult("0");
			response.getResult().setMessage("获取订单评价列表错误");
			return response;
		}

		msg = "获取订单评价列表成功";
		response.getResult().setResult("1");
		response.getResult().setMessage(msg);
		return response;
	}
	
	/**
	 * 提交评价
	 * @param evaluationRequest
	 * @return
	 */
	@ServiceMethod(method = "order.evaluation", version = "1.0", needInSession = NeedInSessionType.NO, httpAction = HttpAction.POST)
	public Response evaluation(EvaluationRequest evaluationRequest) {
		Response response = new Response();
		String msg = "";
		String orderId = evaluationRequest.getOrderId();
		Integer skuId=evaluationRequest.getSkuId();
		Integer userId=evaluationRequest.getUserId();
		//Integer evaluationId=evaluationRequest.getEvaluationId();
		Integer evaluationPrice=evaluationRequest.getEvaluationPrice();
		String evaluationContent =evaluationRequest.getEvaluationContent();
		
		if(orderId==null||StringUtils.isBlank(orderId)||skuId==null||StringUtils.isBlank(skuId.toString())||userId==null||StringUtils.isBlank(userId.toString()))
		{
			response.getResult().setResult("0");
			response.getResult().setMessage("参数不合法");
			return response;
		}
		
		try {
			OrderForm orderForm =  orderFormservice.selectById(orderId);
			if(orderForm==null || orderForm.getUserId().intValue() != userId)
			{
				response.getResult().setResult("0");
				response.getResult().setMessage("订单不存在");
				return response;
			}
			
			OrderEvaluation orderEvaluation = null;
				orderEvaluation = new OrderEvaluation();
//				orderEvaluation.setEvaluationId(evaluationId);
				orderEvaluation.setEvaluationContent(evaluationContent);
				orderEvaluation.setOrderId(Integer.parseInt(orderId));
				orderEvaluation.setSkuId(skuId);
				orderEvaluation.setEvaluationPrice(evaluationPrice);
				orderEvaluation.setEvaluationTime(new Date());
				orderEvaluationService.saveOrUpdate(orderEvaluation);
			orderForm.setIsEvaluate(1);
			orderFormservice.update(orderForm);

		} catch (Exception e) {
			logger.error("evaluation error", e);
			response.getResult().setResult("0");
			response.getResult().setMessage("提交评价错误");
			return response;
		}
		msg = "提交评价成功";
		response.getResult().setResult("1");
		response.getResult().setMessage(msg);
		return response;
	}
	

	
}
